package cn.michael.dev.data.structure.linked.list;

import cn.michael.dev.entity.ListNode;

/**
 * Created by hufenggang on 2021/8/24.
 *
 * 问题描述：单链表的反转
 */
public class Problem206 {

    /**
     * 递归算法实现单链表反转
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode newNode = reverseList(head.next);

        head.next.next = head;
        head.next = null;
        return newNode;
    }

    /**
     * 迭代算法实现单链表反转
     *
     * @param head
     * @return
     */
    public ListNode reverseList1(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }
}
